/**
 * @(#)MobileBelongService.java, 2013-2-13. Copyright 2013 RENREN, Inc. All
 *                               rights reserved. RENREN
 *                               PROPRIETARY/CONFIDENTIAL. Use is subject to
 *                               license terms.
 */
package com.wennimei.service;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wennimei.util.DataUtil;
import com.wennimei.util.FileProcessor;
import com.wennimei.util.FileUtil;
import com.wennimei.util.HttpUtil;

/**
 * @author shichen.feng@renren-inc.com
 */
@Service
public class MobileBelongService {

    private static final Map<String, String> map = new HashMap<String, String>();

    @PostConstruct
    void init() {
        FileUtil.processFile(DataUtil.MOBILE_BELONG, new FileProcessor() {

            @Override
            public void process(String line) {
                try {
                    String[] array = line.split(",");
                    map.put(array[0].trim(), array[1]);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Deprecated
    public String getFromFile(String phone) {
        return map.get(phone.substring(0, 7));
    }

    @SuppressWarnings("unchecked")
    public String get(String phone) {
        String url = "http://apis.juhe.cn/mobile/get?m=" + phone
                + "&key=7e0f669631fbb1620f1d49e33a0ebcc2";
        String json = HttpUtil.get(url);
        Gson gson = new Gson();
        Map<String, Object> res = gson.fromJson(json,
                new TypeToken<Map<String, Object>>() {}.getType());
        Map<String, String> map = (Map<String, String>) res.get("result");
        StringBuilder sb = new StringBuilder();
        sb.append("归属地:" + map.get("province")).append(map.get("city"))
                .append(", 区号：" + map.get("areacode")).append(",")
                .append(map.get("company")).append(map.get("card"));
        return sb.toString();
    }
}
